import React, { useState, useEffect, useRef } from 'react';
import { View, Text, ScrollView, StyleSheet, TouchableOpacity, TextInput, Image } from 'react-native';
import { Toast, Flex } from "@ant-design/react-native";
import FcButton from '@/components/FcButton';
import FcModal from '@/components/FcModal';
import NoData from '@/components/NoData';

import {useGetListQuery} from "@/store/api/contentManage/contentManageApi";

type Props = {
  isOpen?: boolean,
  titleText?: string,
  dateType?: string,
  dateValue?: string,
  dateRange?: Array<string>,
  onClose?: Function,
  onConfirm?: Function,
}
const CopyWriting = ({isOpen, titleText, dateType, dateValue, dateRange, onClose, onConfirm}: Props) => {
  const [listParams, setListParams] = useState({
    pageNo: 1,
    pageSize: 20,
    content: '',
  })
  const [writingList,setWritingList] = useState<any>([])
  const [searchText, setSearchText] = useState<any>('');
  const [isDetection, setIsDetection] = useState(false);
  const [detectionData, setDetectionData] = useState<any>({});
  
  const {data:listDataRef,refetch:listRefetch} = useGetListQuery(listParams)

  useEffect(() => {
    if(listDataRef?.code === 200){
      let list = listDataRef?.result?.records || []
      let updatedList = list.map((item:any) => ({
        ...item,
        sensitiveResult: item.sensitiveResult ? JSON.parse(item.sensitiveResult) : null,
      }));
      setWritingList(updatedList)
    }
    
  },[isOpen, listDataRef])

  //选择文案
  const handleCheckCopy = (item:any) => {
    let str = item.content.split(/【发布语】[:：]?/)[1] || ''

    if(!str){
      Toast.info('该文案未生成发布语')
      return
    }

    onConfirm?.(str.replace(/\s+/g, ''));
    handleClose();
  }

  //是否显示全部文案
  const handleShowAll = (index:any) => {
    let arr = JSON.parse(JSON.stringify(writingList))
    arr[index].isShowAll = !arr[index].isShowAll
    setWritingList(arr)
  }

  //文案搜索
  const handleSearch = (val:any) => {
    setSearchText(val)
    setListParams({
      ...listParams,
      pageNo: 1,
      content: val
    })
    listRefetch()
  }

  //关闭
  const handleClose = () => {
    onClose?.(false)
  }

  return (
    <View>
      <FcModal
        isOpen={isOpen}
        onFcModalClose={() => handleClose}
        titleText='选择文案'
        header={
          <TouchableOpacity style={{marginBottom: 12}}>
            <View style={styles.search_wrap}>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 7}}>&#xe641;</Text>
              <TextInput 
                style={styles.search} 
                placeholder={'请输入文案内容'} 
                placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
                onChangeText={(val) => handleSearch(val)}
                value={searchText}
              />
            </View>
          </TouchableOpacity>
        }
        titleBottomBorderWidth={0}
      >
        <View style={{backgroundColor: '#F1F2F4', paddingHorizontal: 16}}>
          {
            writingList.length == 0 ?
            <View style={{flexDirection: 'column',alignItems: 'center',justifyContent: 'center',paddingTop: 60,paddingBottom: 120}}>
              <NoData hintText='暂无数据'/>
            </View>
            :
            writingList.map((item:any, index:any) => (
              <TouchableOpacity key={index} style={styles.writing_item} onPress={()=> handleCheckCopy(item)}>
                {
                  item.content.split(/【标题】[:：]?/)[1]?.split(/【正文】[:：]?/)[0] ?
                  <Text style={{fontWeight: 700, fontSize: 15, paddingHorizontal: 10}}>{ item.content.split(/【标题】[:：]?/)[1]?.split(/【正文】[:：]?/)[0]?.replace(/[\r\n]+/g, '') }</Text>
                  : null
                }
                <Text style={{fontSize: 15, lineHeight: 24}} numberOfLines={item.isShowAll ? null : 3}>{ item.content.split(/【正文】[:：]?/)[1]?.split(/【发布语】[:：]?/)[0] || item.content }</Text>
                
                <Flex justify='between' style={{marginTop: 4, marginBottom: 8}}>
                  <Flex>
                    <Text style={{fontFamily: 'FcIconFont',fontSize: 16,color: 'rgba(0, 0, 0, 0.5)'}}>&#xe675;</Text>
                    <Text style={styles.dese_text}>{ item.createUsername }</Text>
                  </Flex>

                  <View>
                    <Flex justify='between' align='center'>
                      {
                        item.sensitiveResult && !item.sensitiveResult.sensitive ?
                        <Flex>
                          <Text style={{fontFamily: 'FcIconFont',fontSize: 16,color: '#07C160'}}>&#xe66c;</Text>
                          <Text style={styles.dese_text}>文案已脱敏，无违规风险</Text>
                        </Flex>
                        : item.sensitiveResult && item.sensitiveResult.sensitive ?
                        <Flex>
                          <Text style={{fontFamily: 'FcIconFont',fontSize: 16,color: '#FA5151'}}>&#xe638;</Text>
                          <Text style={styles.dese_text}>文案已脱敏，</Text>
                          <TouchableOpacity onPress={()=> {setDetectionData(item.sensitiveResult); setIsDetection(true)}}>
                            <Text style={{color: '#FA5151', fontSize: 12, textDecorationLine: 'underline'}}>查看检测结果</Text>
                          </TouchableOpacity>
                        </Flex>
                        : !item.sensitiveResult ?
                        <Flex>
                          <Text style={{fontFamily: 'FcIconFont',fontSize: 16,color: '#FF9D00'}}>&#xe638;</Text>
                          <Text style={styles.dese_text}>文案未脱敏，请脱敏检测</Text>
                        </Flex>
                        : null
                      }
                    </Flex>
                  </View>
                </Flex>

                <Flex justify='between'>
                  <FcButton
                    onPress={() => handleShowAll(index)}
                    type='default'
                    style={{width: '48.5%', height: 40}}
                    itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                    textName={!item.isShowAll ? '显示全部文案' : '显示更少文案'}
                    borderWidth={1}
                  ></FcButton>
                  <FcButton
                    onPress={() => handleCheckCopy(item)}
                    type='txtJBAndBkJB'
                    style={{width: '48.5%', height: 40}}
                    itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                    textName='导入发布语'
                    borderWidth={1}
                  ></FcButton>
                </Flex>
              </TouchableOpacity>
            ))
          }
        </View>
      </FcModal>

      <FcModal
        isOpen={isDetection}
        onFcModalClose={() => setIsDetection(false)}
        titleText={'内容脱敏检测'}
        titleBottomBorderWidth={0}
        style={{height: 'auto', paddingHorizontal: 16}}
      >
        <View style={{paddingBottom: 10}}>
          <Text style={styles.check_md}>
            <Text style={styles.check_md_txt}>脱敏检测目的：</Text>
            敏感词汇可能造成曝光了减少 、平台下架、用户投诉、版权纠纷、法律风险，请认真对待敏感内容检测结果，并对内容进行改善
          </Text>
          {!detectionData.sensitive &&
            <Flex direction='column' justify='center' style={[styles.check_hint, {height: 300}]}>
              <Image style={{width: 126, height: 126}} source={require('@/assets/images/public/no_detection.png')}></Image>
              <Text style={[styles.check_hint_txt, {color: 'rgba(0, 0, 0, 0.5)'}]}>没有发现违规风险！</Text>
            </Flex>
          }

          {detectionData.sensitive &&
            <>
              <View style={styles.check_hint}>
                <Text style={styles.check_hint_txt}>{detectionData.riskAndAdviceSummary}</Text>
              </View>
              {detectionData?.sensitiveDetail?.map((item:any, index:any) =>
                <View style={styles.check_hint} key={index}>
                  <Text style={styles.check_hint_txt}>{index + 1}.** <Text style={{color: '#FA5151'}}>{item.keyword}</Text>**</Text>
                  <Text style={styles.check_hint_txt}>**建议改进**：{item.advice}</Text>
                </View>
              )}
            </>
          }
          <Text style={styles.detection_desc}>-- 预警提示，仅供参考 --</Text>
        </View>
      </FcModal>
    </View>
  )
};

const styles = StyleSheet.create({
  search_wrap: {
    flexDirection: 'row',
    alignItems: "center",
    backgroundColor: '#F1F2F4',
    borderRadius: 9,
    marginHorizontal: 16,
    height: 40,
    paddingHorizontal: 14
  },
  search: {
    flex: 1,
    height: '100%',
    color: 'rgba(0,0,0,0.9)'
  },
  writing_item: {
    backgroundColor: '#FFF',
    borderRadius: 8,
    marginTop: 10,
    padding: 12,
  },
  dese_text: {
    color: 'rgba(0, 0, 0, 0.5)',
    fontSize: 12,
    marginLeft: 5,
  },
  check_md: {
    paddingHorizontal: 11,
    paddingVertical: 12,
    borderRadius: 8,
    color: 'rgba(0,0,0,0.9)',
    backgroundColor: '#F1F2F4',
    lineHeight: 18,
    fontSize: 12
  },
  check_md_txt: {
    color: '#FA5151'
  },
  check_hint: {
    marginTop: 12,
  },
  check_hint_txt: {
    lineHeight: 24,
    fontSize: 15,
    color: 'rgba(0,0,0,0.9)',
  },
  detection_desc: {
    color: 'rgba(0, 0, 0, 0.2)',
    fontSize: 10,
    textAlign: 'center',
    marginTop: 30,
  }
})

export default CopyWriting;